package org.grow.bmeans.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.grow.bmeans.dao.MaterialMapper;
import org.grow.bmeans.entity.Material;
import org.grow.bmeans.entity.MaterialQueryCondition;
import org.grow.common.dto.PagedResults;
import org.grow.common.exception.ElNoticeException;
import org.grow.support.service.CodeGene;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: xwg
 * @CreateDate: 2022/2/20
 */

@RestController
@RequestMapping("/bmeans/material")
public class MaterialController {

    public static final String MATERIAL_CODE_PREFIX = "MM";
    @Autowired
    private ThreadLocal<CodeGene> codeGeneThreadLocal;
    @Autowired
    private MaterialMapper materialMapper;


    @PostMapping("/insert")
    public Material insert(@RequestBody Material material) {
        material.setMaterialCode(codeGeneThreadLocal.get().nextCode(MATERIAL_CODE_PREFIX));
        material.setAbandoned(false);
        int insert = materialMapper.insert(material);
        if (insert == 0) {
            throw new ElNoticeException("insert failed");
        }
        return material;
    }


    @GetMapping("/find/{code}")
    public Material find(@PathVariable("code") String code) {
        Material material = materialMapper.selectById(code);
        return material;
    }

    @PutMapping("/modify")
    public Material modify(@RequestBody Material material) {
        int i = materialMapper.updateById(material);
        if (i == 0) {
            throw new ElNoticeException("更新失败" + material.getDescription());
        }
        return material;
    }

    @PostMapping("/query")
    public PagedResults<Material> query(@RequestBody MaterialQueryCondition materialQueryCondition) {
        IPage<Material> p = Page.of(materialQueryCondition.getPageNum(), materialQueryCondition.getPageSize());
        IPage<Material> iPage = materialMapper.dynamicQuery(p, materialQueryCondition);
        return new PagedResults<Material>(iPage.getTotal(), iPage.getRecords());
    }
}
